const Router = require('koa-router');
const router = new Router();
const {db, Op, QueryTypes} = require("../models/db");
// 保存赠品
router.post('/send/save', async ctx => {
    try {
        let user = ctx.user
        let body = ctx.request.body
        let formData = ctx.request.body.formData
        const tenantId = user.tenantId;
        const uid = user.id;
        let invId = 0
        let buId = 0
        let sendInvId = 0
        let buyQty = 0
        let sendQty = 0
        const calType = '按比例送';
        let id = 0
        if(formData) {
            invId = formData.invId ? formData.invId : 0;
            buId = formData.buId ? formData.buId : 0;
            sendInvId = formData.sendInvId ? formData.sendInvId : 0;
            buyQty = formData.buyQty ? formData.buyQty : 0;
            sendQty = formData.sendQty ? formData.sendQty : 0;
            id = formData.id ? formData.id : 0;
            sendUnit = formData.sendUnit ? formData.sendUnit : null;
        }
        if (!buyQty) {
            return ctx.err('请输入买数量')
        }
        if (!sendQty) {
            return ctx.err('请输入赠数量')
        }
        if (!invId) {
            return ctx.err('请输选择商品')
        }
        if (id) {
            let dec = await db.models['send'].findOne({
                where: {
                    tenantId,
                    buId,
                    invId,
                    sendInvId,
                    buyQty,
                    sendQty,
                    stat: 1,
                    id: {
                        [Op.ne]: id
                    }
                }
            })
            if (dec) {
                return ctx.err('已经存在相同的政策');
            }
            let save = {
                tenantId,
                cby: uid,
                buId,
                sendInvId,
                buyQty,
                sendQty,
                invId,
                stat: 1,
                calType,
            }
            await db.models['send'].update(save, {
                where: {
                    id
                }
            })
        }
        else {
            let dec = await db.models['send'].findOne({
                where: {
                    tenantId,
                    buId,
                    invId,
                    sendInvId,
                    buyQty,
                    sendQty,
                    sendUnit,
                    stat: 1
                }
            })
            if (dec) {
                return ctx.err('已经存在相同的政策');
            }
            let save = {
                tenantId,
                cby: uid,
                buId,
                sendInvId,
                buyQty,
                sendQty,
                sendUnit,
                invId,
                stat: 1,
                calType,
            }
            await db.models['send'].create(save)
        }

        return ctx.suc('保存成功');
    }
    catch (e) {
        return ctx.err(e);
    }
})

module.exports = router;

